package com.risen.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.beetl.sql.core.JavaType;
import org.beetl.sql.core.NameConversion;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.db.ColDesc;
import org.beetl.sql.core.db.MetadataManager;
import org.beetl.sql.core.db.TableDesc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.risen.entity.Attribute;
import com.risen.entity.Entity;
import com.risen.utils.Page;

/**
 * 代码生成器
 * 
 */
@Service
public class CodeGenService {
	
	@Autowired
	SQLManager sqlManager;

	public Page<Entity> getAllEntityInfo(Integer page,Integer limit, String key) {
		if(page==null||page<0) {
			page = 1;
		}
		if(limit==null) {
			limit = 10;
		}
		
		List<Entity> list = new ArrayList<Entity>();
		Page<Entity> pages = new Page<>();
		
		MetadataManager meta = sqlManager.getMetaDataManager();
		Set<String> set = meta.allTable();
		if(StringUtils.hasText(key)) {
			for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
				String string = iterator.next();
				if(!string.toLowerCase().contains(key.toLowerCase())) {
					iterator.remove();
				}
			}
		}
		List<String> tables = new ArrayList<>(set);
		pages.setCount(set.size());
		int len = page*limit <= tables.size() ? page*limit: tables.size();
		int start = (page-1)*limit;
		for(int i = start; i<len; i++) {
			list.add(getEntitySimpleInfo(tables.get(i)));
		}
		pages.setData(list);
		return pages;
	}

	public Entity getEntitySimpleInfo(String table) {
		MetadataManager meta = sqlManager.getMetaDataManager();
		TableDesc tableDesc = meta.getTable(table);
		NameConversion nc = sqlManager.getNc();
		if (tableDesc == null) {
			return null;
		}
		Entity e = new Entity();
		e.setName(nc.getClassName(table));
		e.setComment(tableDesc.getRemark());
		e.setTableName(table);
		return e;
	}

	public Entity getEntityInfo(String table) {
		MetadataManager meta = sqlManager.getMetaDataManager();
		NameConversion nc = sqlManager.getNc();
		TableDesc tableDesc = meta.getTable(table);
		if (tableDesc == null) {
			return null;
		}
		Entity e = new Entity();
		e.setName(nc.getClassName(table));
		e.setComment(tableDesc.getRemark());
		e.setTableName(table);
		e.setCode(getEntityCode(e.getName()));

		Set<String> cols = tableDesc.getCols();
		ArrayList<Attribute> attrs = new ArrayList<Attribute>();
		for (String col : cols) {
			ColDesc desc = tableDesc.getColDesc(col);
			Attribute attr = new Attribute();
			attr.setColName(col);
			attr.setName(nc.getPropertyName(col));
			if (tableDesc.getIdNames().contains(col)) {
				// TODO,代码生成实际上用了一个Id，因此具备联合主键的，不应该生成代码
				attr.setId(true);
				e.setIdAttribute(attr);
			}
			attr.setComment(desc.remark);
			String type = JavaType.getType(desc.sqlType, desc.size, desc.digit);
			if (type.equals("Double")) {
				type = "BigDecimal";
			}
			if (type.equals("Timestamp")) {
				type = "Date";
			}
			attr.setJavaType(type);
			setGetDisplayName(attr);
			attrs.add(attr);
		}
		e.setList(attrs);

		return e;
	}

	private String getEntityCode(String s) {
		// 找到最后一个大写字母，以此为变量名
		if (Character.isLowerCase(s.charAt(0)))
			return s;
		else
			return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();

	}

	/* 根据数据库注释来判断显示名称 */
	private void setGetDisplayName(Attribute attr) {
		String comment = attr.getComment();
		if (StringUtils.isEmpty(comment)) {
			attr.setDisplayName(attr.getName());
			return;
		}
		String displayName = null;
		int index = comment.indexOf(",");
		if (index != -1) {
			displayName = comment.substring(0, index);
			attr.setDisplayName(displayName);
		} else {
			attr.setDisplayName(comment);
		}
	}

	public void refresh() {
		sqlManager.refresh();
	}
	
}
